<template>
  <el-form ref="spuForm" label-width="100px" :model="spuInfo" class="demo-ruleForm" :rules="rules">
    <el-form-item label="Spu名称" prop="spuName">
      <el-input style="width: 500px" v-model="spuInfo.spuName" placeholder="请输入名称"></el-input>
    </el-form-item>
    <el-form-item label="Spu品牌" prop="tmId">
      <el-select placeholder="请选择品牌" v-model="spuInfo.tmId">
        <el-option v-for="trademark in trademarkList" :key="trademark.id" :label="trademark.tmName" :value="trademark.id"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="Spu描述" prop="description" type="textarea">
      <el-input type="textarea" v-model="spuInfo.description" placeholder="请输入描述信息"></el-input>
    </el-form-item>
    <el-form-item label="Spu图片" prop="spuImageList">
      <el-upload
        action="/dev-api/admin/product/fileUpload"
        :limit="3"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
        accept=".jpg,.jpeg,.png "
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :class="{ 'spu-image-upload': spuInfo.spuImageList.length >= 3 }"
        :file-list="spuImageList"
      >
        <i class="el-icon-plus"></i>
        <div class="el-upload__tip" slot="tip">只能上传jpg/png/jpeg文件,且不超过2M</div>
      </el-upload>
      <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="" />
      </el-dialog>
    </el-form-item>
    <el-form-item label="销售属性" prop="spuSaleAttrList">
      <el-select :placeholder="`还剩下${formatBaseSaleAttrList.length}个销售属性`" v-model="spuInfo.spuSaleAttr">
        <el-option v-for="baseSaleAttr in formatBaseSaleAttrList" :key="baseSaleAttr.id" :label="baseSaleAttr.name" :value="baseSaleAttr.name"></el-option>
      </el-select>
      <el-button type="primary" icon="el-icon-plus" style="margin: 0 0 20px 10px" :disabled="!spuInfo.spuSaleAttr" @click="addSpuSaleAttr">添加销售属性值</el-button>
      <el-table border style="width: 100%" :data="spuInfo.spuSaleAttrList">
        <el-table-column prop="date" type="index" label="序号" width="80" align="center"> </el-table-column>
        <el-table-column prop="saleAttrName" label="属性名" align="center"> </el-table-column>
        <el-table-column prop="address" label="属性值列表" align="center">
          <template v-slot="{ row }">
            <el-tag :key="tag.saleAttrValueName" v-for="tag in row.spuSaleAttrValueList" closable :disable-transitions="false" @close="handleClose(tag, row)">
              {{ tag.saleAttrValueName }}
            </el-tag>
            <el-input class="input-new-tag" v-if="row.inputVisible" v-model.trim="inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(row)" @blur="handleInputConfirm(row)"> </el-input>
            <el-button v-else class="button-new-tag" size="small" @click="showInput(row)">+ New Tag</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template v-slot="{ $index }">
            <el-tooltip content="删除属性" placement="top">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteSpuSaleAttr($index)" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm">确定</el-button>
      <el-button @click="$emit('update:visible', 1)">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { reqAllTrademarkList, reqBaseSaleAttrList, reqSaveSpuInfo, reqGetSpuImageList, reqGetSpuSaleAttrList, reqUpdateSpuInfo } from '@/api/product/spu'
import { mapState } from 'vuex'
export default {
  name: 'SaveSpu',
  data() {
    const spuImageListValidate = (rule, value, callback) => {
      // if (!value.length) {
      //   return callback(new Error('请至少上传一张图片'))
      // }
      callback()
    }
    const spuSaleAttrListValidate = (rule, value, callback) => {
      if (!value.length) {
        return callback(new Error('请选择一个销售属性'))
      }
      if (!value.every((item) => item.spuSaleAttrValueList.length !== 0)) {
        return callback(new Error('销售属性值不能为空'))
      }
      callback()
    }

    return {
      dialogImageUrl: '', // 图片的链接
      dialogVisible: false, // 上传图片成功后的预览
      trademarkList: [], // 所有的品牌数据列表
      baseSaleAttrList: [], // 所有的基础销售属性列表
      // inputVisible: false,
      inputValue: '', // 三级id
      spuImageList: [],
      spuInfo: {
        spuName: '', // spu的名称
        spuImageList: [], // SPU图片
        spuSaleAttr: '', // 收集选中的属性
        spuSaleAttrList: [], // 基本销售属性,属性列表
        description: '', // spu描述
        tmId: '', //品牌
        category3Id: '',
        ...this.currentInfo
      },
      rules: {
        spuName: [{ required: true, message: '请输入SPU名称', trigger: 'blur' }],
        tmId: [{ required: true, message: '请选择所属品牌', trigger: 'change' }],
        description: [{ required: true, message: '请输入SPU描述', trigger: 'blur' }],
        spuImageList: [{ required: true, validator: spuImageListValidate, trigger: 'change' }],
        spuSaleAttrList: [{ required: true, validator: spuSaleAttrListValidate, trigger: 'blur' }]
      }
    }
  },
  props: {
    currentInfo: {
      type: Object,
      default: () => {}
    }
  },
  async mounted() {
    try {
      let promises = [reqAllTrademarkList(), reqBaseSaleAttrList()]
      const { id } = this.spuInfo
      if (id) {
        promises = promises.concat([reqGetSpuImageList(id), reqGetSpuSaleAttrList(id)])
      }
      const [responseAllTrademarkList, responseBaseSaleAttrList, responseSpuImageList, responseSpuSaleAttrList] = await Promise.all(promises)

      this.trademarkList = responseAllTrademarkList.data
      this.baseSaleAttrList = responseBaseSaleAttrList.data

      if (responseSpuImageList && responseSpuSaleAttrList.code === 200) {
        // this.spuInfo.spuImageList = responseSpuImageList.data
        this.spuImageList = responseSpuImageList.data.map((item) => {
          return {
            name: item.imgName,
            url: item.imgUrl
          }
        })
        this.spuInfo.spuSaleAttrList = responseSpuSaleAttrList.data
      }
    } catch (err) {
      this.$message.error('获取数据失败')
    }
  },
  computed: {
    formatBaseSaleAttrList() {
      return this.baseSaleAttrList.filter((baseSaleAttr) => {
        return !this.spuInfo.spuSaleAttrList.find((item) => {
          return baseSaleAttr.name === item.saleAttrName
        })
      })
    },
    // formartSpuImageList() {
    //   return this.spuInfo.spuImageList.map((item) => {
    //     return {
    //       name: item.imgName,
    //       url: item.imgUrl
    //     }
    //   })
    // },
    ...mapState('category', ['category3Id'])
  },
  methods: {
    //删除图片时调用
    handleRemove(file, fileList) {
      //file为删除的图片
      //fileList是剩余的图片
      // console.log(file, fileList)

      // this.spuInfo.spuImageList.fileList
      this.spuImageList.fileList
    },
    //预浏览时调用
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    //上传成功之后调用
    handleAvatarSuccess(res, file, fileList) {
      // this.spuInfo.spuImageList = fileList
      this.spuImageList = fileList
      //res上传成功后,服务器响应回来的数据
      //file是一个大对象,不但包含res中的内容还包含图片原有的数据
      // this.imageUrl = URL.createObjectURL(file.raw)
      // this.tmfrom.logoUrl = res.data //上传成功之后的图片地址储存在这里
      // //上传图片成功之后,移除校验提示
      // this.$refs.spuForm.clearValidate('spuImageList')
    },
    //上传之前调用
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg,image/jpg'
      const imgArr = ['image/jpeg', 'image/jpg', 'image/png']
      const isJPG = imgArr.includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    //添加属性
    addSpuSaleAttr() {
      const spuSaleAttrList = this.spuInfo.spuSaleAttrList
      // if (spuSaleAttrList.length && spuSaleAttrList[spuSaleAttrList.length - 1].spuSaleAttrValueList.length === 0) {
      //   return this.$message.error('属性值不能为空')
      // }
      if (!spuSaleAttrList.every((item) => item.spuSaleAttrValueList.length !== 0)) {
        this.$message.error('属性值不能为空')
        return
      }
      spuSaleAttrList.push({
        inputVisible: false, // 控制当前对象所在行的按钮和输入框
        saleAttrName: this.spuInfo.spuSaleAttr,
        spuSaleAttrValueList: []
      })
      this.spuInfo.spuSaleAttr = ''
    },

    //删除属性
    deleteSpuSaleAttr(index) {
      this.spuInfo.spuSaleAttrList.splice(index, 1)
    },
    // 动态编辑标签相关
    handleClose(tag, row) {
      // row.spuSaleAttrValueList.splice(this.dynamicTags.indexOf(tag), 1)
      row.spuSaleAttrValueList.splice(row.spuSaleAttrValueList.indexOf(tag), 1)
    },

    showInput(row) {
      // row.inputVisible = true
      //使用vue.$set把数据变成响应式的
      this.$set(row, 'inputVisible', true)
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    //失去焦点
    handleInputConfirm(row) {
      let inputValue = this.inputValue

      // console.log(this.baseSaleAttrList)
      // console.log(row.saleAttrName);
      if (inputValue) {
        // row.spuSaleAttrValueList.push(inputValue)
        if (row.spuSaleAttrValueList.find((item) => item.saleAttrValueName === inputValue)) {
          this.$message.error('属性值不能重复！')
          row.inputVisible = false
          this.inputValue = ''
          return
        }

        const id = this.baseSaleAttrList.find((item) => item.name === row.saleAttrName).id

        row.spuSaleAttrValueList.push({
          baseSaleAttrId: id, // 销售属性对应的id
          saleAttrName: row.saleAttrName, // 属性名 ，比如颜色 规格  尺寸
          saleAttrValueName: inputValue // 属性值 比如颜色中的红色  蓝色  紫色
        })
      }

      row.inputVisible = false // 将输入框切换成按钮
      this.inputValue = '' // 清空输入框中的值 以便下一次继续添加
    },
    //添加spu
    submitForm() {
      this.$refs.spuForm.validate(async (valid) => {
        if (valid) {
          this.spuInfo.category3Id = this.category3Id
          // this.spuInfo.spuImageList = this.spuInfo.spuImageList.map((item) => {
          this.spuInfo.spuImageList = this.spuImageList.map((item) => {
            return {
              imgName: item.name,
              imgUrl: item.response ? item.response.data : item.url
            }
          })
          if (this.spuImageList.length === 0) {
            this.$message.error('请至少添加一张图片！')
            return
          }
          const { id } = this.spuInfo
          let result
          if (id) {
            result = await reqUpdateSpuInfo(this.spuInfo)
          } else {
            result = await reqSaveSpuInfo(this.spuInfo)
          }
          if (result.code === 200) {
            this.$message.success(`${id ? '更新' : '添加'}成功！`)
            //跳转spu列表页
            this.$emit('update:visible', 1)
          } else {
            this.$message.error('添加失败！')
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scope>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>